package com.videoaggre.zcl.utils

import android.view.View
import android.widget.CheckBox
import android.widget.CompoundButton
import android.widget.TextView
import com.videoaggre.zcl.common.toastMessageLong
import com.videoaggre.zcl.helper.OnValidationResultListener
import com.videoaggre.zcl.helper.TextWatcher

class VariableViewUtils {
    private val variableTextView: MutableList<TextView> = mutableListOf()
    private val variableCheckBox: MutableList<CheckBox> = mutableListOf()
    private var mOnValidationResultListener: OnValidationResultListener? = null
    private var mOnValidationInterceptListener: ((View) -> Boolean?)? = null
    private var isShowHint = false

    /** 验证结果接收者 */
    fun addOnValidationResultListener(onValidationResultListener: OnValidationResultListener? = null) {
        mOnValidationResultListener = onValidationResultListener
    }

    /** 自定义验证 */
    fun addOnValidationInterceptListener(onValidationInterceptListener: ((View) -> Boolean?)? = null) {
        mOnValidationInterceptListener = onValidationInterceptListener
    }

    fun addTextView(textView: TextView) {
        textView.addTextChangedListener(TextWatcher { validator() })
        variableTextView.add(textView)
    }

    fun addCheckBox(checkBox: CheckBox) {
        checkBox.setOnCheckedChangeListener(this::onCheckedChanged)
        variableCheckBox.add(checkBox)
    }

    private fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {
        validator()
    }

    /** 验证并且设置按钮状态 */
    fun validator() {
        isShowHint = false
        mOnValidationResultListener?.enable(textValidator() && checkBoxValidator())
    }

    /** 验证并且提示hint设置的信息*/
    fun clickValidator(): Boolean {
        isShowHint = true
        return textValidator() && checkBoxValidator()
    }

    private fun textValidator(): Boolean {
        for (tv in variableTextView) {
            val isNotEmpty =
                when (val validationIntercept = mOnValidationInterceptListener?.invoke(tv)) {
                    null -> tv.text.isNotEmpty()
                    else -> validationIntercept
                }
            if (!isNotEmpty) {
                if (isShowHint) tv.hint.toastMessageLong()
                return false
            }
        }
        return true
    }

    private fun checkBoxValidator(): Boolean {
        for (checkBox in variableCheckBox) {
            val isChecked =
                when (val validationIntercept = mOnValidationInterceptListener?.invoke(checkBox)) {
                    null -> checkBox.isChecked
                    else -> validationIntercept
                }
            if (!isChecked) {
                if (isShowHint && checkBox.text.isNotEmpty()) toastMessageLong(
                    checkBox.text.toString()
                )
                return false
            }
        }
        return true
    }
}